package com.misboot.document.utils.wps;


import cn.ewsd.common.bean.LoginInfo;
import com.misboot.document.config.ReqKeys;
import com.misboot.document.propertie.RedirectProperties;
import com.misboot.document.propertie.WpsProperties;
import com.misboot.document.utils.wps.file.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Component
public class WpsUtil {


    @Autowired
    private static WpsProperties wpsProperties;

    @Autowired
    private  static RedirectProperties redirect;

    @Autowired
    public WpsUtil(WpsProperties wpsProperties, RedirectProperties redirect) {
        this.wpsProperties = wpsProperties;
        this.redirect = redirect;
    }

    public static String getWpsUrl(Map<String, String> values, String fileType, String fileId, String appsecret, String domain ) throws UnsupportedEncodingException {
        String keyValueStr = SignatureUtil.getKeyValueStr(values);
        String signature = SignatureUtil.getSignature(values, appsecret);
        String fileTypeCode = FileUtil.getFileTypeCode(fileType);

        String str= domain + fileTypeCode + "/" + fileId + "?"   + keyValueStr + "_w_signature=" + signature;
           return    str;
    }


    private static String getUrlParam(Map<String, String> params) throws UnsupportedEncodingException {
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (builder.length() > 0) {
                builder.append('&');
            }
            builder.append(URLEncoder.encode(entry.getKey(), "utf-8")).append('=').append(URLEncoder.encode(entry.getValue(), "utf-8"));
        }
        return  builder.toString();
    }


    public static String getTemplateWpsUrl(String fileType, String userId, String puuid, String bucket) throws UnsupportedEncodingException {
        Map<String, String> values = new HashMap<String, String>() {
            {
//                put(redirect.getKey(), redirect.getValue());//加上就无法打开模板新建页面，显示非法签名
                put(ReqKeys.APP_ID_KEY, wpsProperties.getAppid());
                put("_w_redirectkey", "123456");
                put(ReqKeys.USER_ID_KEY, userId);
                put("_w_puuid", puuid);
                put("_w_createName", LoginInfo.getUserName());
                put("_w_createNameId", LoginInfo.getUserNameId());
                put("_w_bucket", bucket);
            }
        };
        String keyValueStr = SignatureUtil.getKeyValueStr(values);
        String signature = SignatureUtil.getSignature(values, wpsProperties.getAppsecret());
        String fileTypeCode = FileUtil.getTypeCode(fileType);

        return wpsProperties.getDomain() + fileTypeCode + "/new/0" + "?"
                + keyValueStr + ReqKeys.SIGNATURE_KEY  + "=" + signature;
    }

}
